import { defineStore } from "pinia";
import { setAuthorizationToken } from "../utils/request";
import { AuthAPI } from "../apis";
import { ElMessage } from "element-plus";

export default defineStore("user", {
  state: () => {
    return {
      token: null,
      isUserLoading: false, // 用户登录中
      user: {
        user_id: "",
        mobile: "",
        mobile_confirmed: false,
        identity_status: "EMPTY",
      },
      timer: null,
    };
  },
  actions: {
    // 只是加载，真正的登录需要提交请求
    async loginFromLocalStorage() {
      // 加载 token
      const token = localStorage.getItem("token");
      if (token) {
        this.token = token;
        setAuthorizationToken(token);
      }
    },

    async login(form) {
      this.isUserLoading = true;
      try {
        const { status, data: user, message } = await AuthAPI.login(form);

        if (status !== 200) {
          ElMessage({
            message,
            type: "error",
          });
          throw new Error(message);
        }
        // 登录成功
        this.user = user;
        return user;
      } finally {
        this.isUserLoading = false;
      }
    },
    async register(form) {
      this.isUserLoading = true;
      try {
        // 填写默认验证码
        const {
          data: verify_code,
          status: verify_code_status,
          message: verify_code_message,
        } = await AuthAPI.getVerifyCode({
          verify_field: "MOBILE",
          mobile: form.mobile,
          scene: "REGISTER",
        });
        if (verify_code_status !== 200) {
          ElMessage({
            message: verify_code_message,
            type: "error",
          });
          throw new Error(verify_code_message);
        }
        form.verify_code_id = verify_code.verify_code_id;

        const { status, data: user, message } = await AuthAPI.register(form);
        if (status !== 200) {
          ElMessage({
            message,
            type: "error",
          });
          throw new Error(message);
        }

        this.user = user;
        return user;
      } finally {
        this.isUserLoading = false;
      }
    },
    logout() {
      clearInterval(this.timer);
      this.token = null;
      localStorage.removeItem("token");

      this.user = {
        user_id: "",
        mobile: "",
        mobile_confirmed: false,
      };
      AuthAPI.logout().then();
    },
  },
});
